package model.camera;

import java.util.ArrayList;

import model.OnScreen;
import model.location.ReferencePoint;
import model.location.ReferencePointFactory;
import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.AsyncTask;
import android.util.Log;

public class CameraPreviewCallback implements Camera.PreviewCallback 
{
	@Override
	public void onPreviewFrame(byte[] bytes, Camera camera) 
	{
		Size previewSize = camera.getParameters().getPreviewSize();
		
		new Decoder(previewSize).execute(bytes);
//		new ZBarDecoder(previewSize).execute(bytes);
	}
	
	private class ZBarDecoder extends AsyncTask<byte[], Void, SymbolSet>
	{
		private Size previewSize;
		private ImageScanner scanner;
		
		public ZBarDecoder(Size previewSize)
		{
			this.previewSize = previewSize;
			
			scanner = new ImageScanner();
			
	        scanner.setConfig(0, Config.X_DENSITY, 3);
	        scanner.setConfig(0, Config.Y_DENSITY, 3);
		}
		
		@Override
		protected SymbolSet doInBackground(byte[]... bytes) 
		{
			Image barcode = new Image(previewSize.width, previewSize.height, "GREY");
	        barcode.setData(bytes[0]);

	        int result = scanner.scanImage(barcode);
	        Log.d("CameraPreviewCallback", String.format("result: %d", result));
	        
	        ArrayList<ReferencePoint> refPoints = new ArrayList<ReferencePoint>();
	        
	        if (result > 1) 
	        {       	
	            return scanner.getResults();
            }
	        return null;
		}
		
		@Override
		protected void onPostExecute(SymbolSet syms) 
		{
			ArrayList<ReferencePoint> refPoints = new ArrayList<ReferencePoint>();
			
			if(syms != null)
			{
				for (Symbol sym : syms) 
	            {
					if(qrValueEqualsOurFormat(sym.getData()));
						refPoints.add(ReferencePointFactory.createReferencePoint(sym));
	            }
			}
			
			 Log.d("CameraPreviewCallback", String.format("correct results: %d", refPoints.size()));
			 //TODO: call send to screen
			 //OnScreen.getInstance().updateReferencePointList(refPoints);
			 
			 CameraManager.addCallbackBuffer();
		}		
		
		private boolean qrValueEqualsOurFormat(String result)
		{
			for (char c : result.toCharArray())
		    {
		        if (Character.isDigit(c)) continue; // if the char is a digit -> go check the next char.
		        if(c != '_') return false;			// otherwise check if it is an underscore, if it is not an underscore, return false
		    }
			
			return result.split("_").length == 3;
		}
	}
}
